const {
  Base
} = require('../../utils/base.js')
const {
  MemberModel
} = require('../../utils/member-model.js')
const {
  Config
} = require('../../utils/config.js')
const memberModel = new MemberModel()
const http = new Base()
const app = getApp()
Component({
  properties: {
    authShow: {
      type: Boolean,
      value: false
    },
    phoneShow: {
      type: Boolean,
      value: false
    },
    encryptedDataUser: {
      type: String,
      value: ''
    },
    ivUser: {
      type: String,
      value: ''
    },
    activityType: {
      type: null
    },
    activityId: {
      type: String,
      value: ''
    },
    /**
     * source 来源
     * 2: 机台登录
     * 3: 集卡活动
     * 4: 收银台
     * 6: 刷卡器
     * 7: 分享送红包，分享限时抢购，分享小游戏，分享集卡活动
     */
    source: {
      type: null
    },
    channel: {
      type: null
    },
    operator: {
      type: String,
      value: ''
    },
    resourcesId: {
      type: String,
      value: ''
    }
  },
  observers: {
    source(val) {
      val === this.data.source
    }
  },
  data: {
    code: '',
    formIds: '',
    dialogShow: false,
    coupons: [],
    isSubscribe: false
  },
  attached() {
    this.getCode()
  },
  methods: {
    getCode() {
      wx.login({
        success: ({
          code
        }) => {
          this.setData({
            code
          })
        }
      })
    },
    getUserInfo({
      detail
    }) {
      const {
        encryptedData,
        iv
      } = detail
      if (encryptedData) {
        this.setData({
          encryptedDataUser: encryptedData,
          ivUser: iv,
          authShow: false,
          phoneShow: true
        })
      } else {
        this.triggerEvent('authfail', {})
      }
    },
    getPhoneNumber({
      detail
    }) {
      this.setData({
        phoneShow: false
      })
      const {
        encryptedData,
        iv
      } = detail
      if (encryptedData) {
        this.setData({
          encryptedDataPhone: encryptedData,
          ivPhone: iv,

        })
        this.register()
      } else {
        this.triggerEvent('authfail', {})
      }
    },
    refuseAuth() {
      this.setData({
        authShow: false
      })
      this.triggerEvent('refuse', {})
    },
    refusePhone() {
      this.setData({
        phoneShow: false
      })
      this.triggerEvent('refuse', {})
    },
    formSubmit(e) {
      this.getSubscribeMessage()
      // this.setData({
      //   formIds: e.detail.formId
      // })
    },
    register() {
      let params = {
        sourcePartnerSign: app.globalData.sourcePartnerSign,
        code: this.data.code,
        encryptedDataUser: this.data.encryptedDataUser,
        ivUser: this.data.ivUser,
        encryptedDataPhone: this.data.encryptedDataPhone,
        ivPhone: this.data.ivPhone,
        appId: Config.appId,
        formId: this.data.formIds,
        shareFlag: !!app.globalData.isShare,
        shareMemberId: app.globalData.shareMemberId,
        shareActivityId: app.globalData.activityId,
        activityType: this.data.activityType === null ? undefined : this.data.activityType,
        activityId: this.data.activityId,
        source: this.data.source === null ? undefined : this.data.source,
        channel: this.data.channel === null ? undefined : this.data.channel,
        operatorId: this.data.operator,
        resourcesId: this.data.resourcesId === null ? undefined : this.data.resourcesId
      }
      wx.checkSession({
        success: () => {
          http.request({
            url: '/wechat/applet/user/register',
            data: params,
            sCallback: ({
              data,
              error,
              status
            }) => {
              if (status === 200) {
                wx.setStorageSync('token', data.token)
                app.globalData.isLogin = true
                // this.assetTransfer()
                if (data.register) {
                  this.registerGift()
                } else {
                  this.triggerEvent('refresh', {})
                }
              } else {
                this.getCode()
                wx.showToast({
                  title: `${error}`,
                  icon: 'none'
                })
                this.triggerEvent('authfail', {})
              }
            },
            eCallback: () => {
              this.getCode()
              wx.showToast({
                icon: 'none',
                title: '会员注册失败'
              })
              this.triggerEvent('authfail', {})
            }
          })
        },
        fail: () => {
          this.getCode()
          wx.showToast({
            icon: 'none',
            title: '时间太长，请重新登录'
          })
          this.triggerEvent('authfail', {})
        }
      })
    },
    registerGift() {
      memberModel.registerGift({
        partnerSign: app.globalData.sourcePartnerSign,
        merchantId: wx.getStorageSync('merchantId')
      }).then(data => {
        data = data || []
        if (data.length) {
          this.setData({
            dialogShow: true,
            coupons: data
          })
        } else {
          this.triggerEvent('refresh', {})
        }
      }).catch(() => {
        this.triggerEvent('refresh', {})
      })
    },
    closeDialog() {
      this.setData({
        dialogShow: false
      })
      this.triggerEvent('refresh', {})
    },
    /**
     * 1.点击【我知道了】显示订阅消息弹窗
     * 2.点击【积分商城】进入积分详情页面时
     * 3.会员授权成功后
     * 4.点击【会员中心】按钮
     */
    getSubscribeMessage: function () {
      memberModel.subscribeMessage({
        merchantId: wx.getStorageSync('merchantId'),
        position: 3
      }).then(data => {
        if (data && data.length > 0) {
          let tmplId = []
          data.forEach(element => {
            if (element.templateId) {
              tmplId.push(element.templateId)
            }
          })
          if (tmplId.length > 0) {
            wx.requestSubscribeMessage({
              tmplIds: tmplId,
              success(res) {},
              fail(err) {}
            })
          }
        }
      }).catch(err => {
        wx.showToast({
          title: `${err.error}`,
          icon: 'none',
          duration: 2000
        })
      })
    },
  }
})